import qrcode
from PIL import Image
import io

def generate_qr(content):
    """生成二维码并返回 PIL 图像对象"""
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(content)
    qr.make(fit=True)
    return qr.make_image(fill_color="black", back_color="white")

# 在聊天界面中调用的示例
def show_qr_in_chat(st, content):
    try:
        print(f"准备生成二维码，内容: {content}")
        
        if not content:
            print("内容为空，无法生成二维码")
            return
            
        # 生成二维码
        img = generate_qr(content)
        print("二维码生成成功")
        
        # 转换为字节流
        img_bytes = io.BytesIO()
        img.save(img_bytes, format="PNG")
        img_bytes.seek(0)  # 重置字节流位置
        # print("二维码已转换为字节流")
        
        # 添加二维码消息到历史记录
        if "messages" not in st.session_state:
            st.session_state.messages = []
            
        # 重新获取字节流数据
        img_bytes.seek(0)
        img_data = img_bytes.getvalue()
        
        # 添加原始消息
        st.session_state.messages.append({
            "role": "assistant",
            "content": "Your order information has been generated"
        })
        
        # 添加二维码消息
        st.session_state.messages.append({
            "role": "assistant",
            "content": "This is your payment QR code, please scan the code to pay",
            "image": img_data,
            "show_image": True
        })
        
        # print("消息和二维码已添加到历史记录")
        
    except Exception as e:
        print(f"生成二维码时发生错误: {str(e)}")
        st.error(f"生成二维码时发生错误: {str(e)}")
    
